	set more off
	
	global directory "D:\Meniga"
	
	/*************************************************************************
	* 					FINANCIAL AGGREGATION DATA 							 *
	*************************************************************************/
	/*************************************************************************
	* 					CALCULATE AVERAGE DAILY SPENDING 					 *
	*************************************************************************/
	
	use "$directory\daily_panel_reduced_new.dta", clear

	gen mean_exp = (alc + gambling_exp + gaming + lottery_char_exp + lottery_exp + recr + rmf + ca + er + fuel + groc + groupon + hi + hs + insurances + media + pharm + transp)/100
	
	keep ind_id edate mean_exp
	
	preserve
	
		gen first_exp = .
			replace first_exp = edate	if (mean_exp ~= 0 & mean_exp < .)
		
		collapse (min) first_exp, by(ind_id)
				
		
		tempfile first_exp
		
		sort ind_id
		save `first_exp'
			
	restore
	
		/*************************************************************************
		* 				Dropping observations before first expenditure			 *
		*************************************************************************/

		merge m:1 ind_id using `first_exp', nogen
		
		replace mean_exp = .	if edate <  first_exp
		replace mean_exp = 0	if edate >= first_exp & mean_exp >= .
	
	collapse (mean) mean_exp, by(ind_id)
		
		
	tempfile mean_exp
		
	sort ind_id
	save `mean_exp'
	
	/*************************************************************************
	* 							PAYDAY LOANS								 *
	*************************************************************************/
	
	use "$directory\payday_loans_merged.dta", clear

	gen numloans = (payday_loan > 0) if payday_loan < .
	
	replace payday_loan = payday_loan/100
	ren payday_loan loanamnt
		
		********************************************************	
		*** 					TABLE 1						 ***	
		********************************************************	
		
		preserve
		
			drop if loanamnt < 10  
			
			count if numloans == 1
		
			summ loanamnt if numloans == 1, detail

			collapse (sum) numloans (sum) loanamnt, by(ind_id)
			
			gen everpayday = (numloans > 0) if numloans < .
			
			mean everpayday
				
			count						if everpayday == 1
			foreach var in numloans loanamnt {
				summ `var'		if everpayday == 1, detail
			}		
			
		restore
		
		********************************************************	
		
		
	collapse (sum) numloans (sum) loanamnt, by(ind_id)
	
	gen everpayday = (numloans > 0) if numloans < .
	
	
	
	tempfile Payday_Loans
	
	sort ind_id
	save `Payday_Loans'
	
	/*************************************************************************
	* 				NON-SUFFICIENT FUNDS (NSF) CHARGES						 *
	*************************************************************************/
	
	use "$directory\penalty_payments_ready.dta", clear

	replace fit = -fit/100

		********************************************************	
		*** 	SUMMARY STATISTICS of NSF FEES 				***	
		********************************************************	
		
		count if fit_count == 0 & fit > 0 		& fit < .
		count if fit == 0 		& fit_count > 0 & fit_count < .
		
		gen fit_percount = fit/fit_count
			replace fit_percount = 0	if fit_count == 0
		
		summ fit, detail
		summ fit 			if fit > 0, detail
		summ fit_count, detail
		summ fit_count 		if fit_count > 0, detail
		summ fit_percount, detail
		summ fit_percount	if fit_percount > 0, detail
		*/
		********************************************************	
	
	
	ren fit_count numNSF
	collapse (sum) numNSF (sum) fit (mean) fit_percount, by(ind_id)
	
	
		********************************************************	
		*** 	SUMMARY STATISTICS of NSF FEES 				***	
		********************************************************	
		
		summ fit, detail
		summ fit 			if fit > 0, detail
		summ numNSF, detail
		summ numNSF 		if numNSF > 0, detail
		summ fit_percount, detail
		summ fit_percount	if fit_percount > 0, detail
		*/
		********************************************************	
	
	
	ren fit NSFamnt
	
	tempfile NSF
	
	sort ind_id
	save `NSF'
	
	/*************************************************************************
	* 							INCOME										 *
	*************************************************************************/
	
	use "$directory\income_2011_2017.dta" if edate >= td(01feb2011) & edate <= td(31jan2017), clear

	replace amount = amount/100
	clonevar wages = amount
	ren amount income
	
	replace wages = 0	if wages < . & income_source ~= "Salary"
		
	collapse (sum) income (sum) wages, by(ind_id emy)
	collapse (mean) income (mean) wages, by(ind_id)
	
	
	tempfile Income
	
	sort ind_id
	save `Income'

	/*************************************************************************
	* 							LIQUIDITY									 *
	*************************************************************************/
		
	use "$directory\accounts_2014_2017.dta", clear

	foreach var in ca_bal sa_bal ccard_bal ca_lim ccard_lim {
		replace `var' = `var'/100
	}
		
		/*********************************************************************
		* Adjusting for when overdraft or credit card exceeded limits		 *
		*********************************************************************/

		replace sa_bal = 0	if sa_bal < 0
		replace ca_lim = -ca_bal		if ca_bal < 0 		& abs(ca_bal) > ca_lim
		replace ccard_lim = -ccard_bal	if ccard_bal < 0 	& abs(ccard_bal) > ccard_lim

	
	preserve	
		
		gen ca = ca_lim + ca_bal
		gen ca_sa  = ca_lim + ca_bal + sa_bal
		gen ccard = ccard_lim + ccard_bal
		gen liq  = ca_lim + ca_bal + ccard_lim + ccard_bal + sa_bal
		
		
		keep ind_id edate ca sa_bal ca_sa ccard liq
		
		replace edate = edate + 1	
		compress
		
		tempfile timeseries
		
		sort ind_id edate
		save `timeseries'
		
	restore


	gen liquidity  = ca_lim + ca_bal + ccard_lim + ccard_bal + sa_bal
	replace ccard_bal = -ccard_bal
	
	collapse (median) liquidity (median) ca_bal (median) sa_bal (median) ccard_bal, by(ind_id)
	

	tempfile Liquidity
	
	sort ind_id
	save `Liquidity'
		
	/*************************************************************************
	* 			MERGING FINANCIAL AGGREGATION DATA 							 *
	*************************************************************************/
	
	use `Payday_Loans', clear
	
	sort ind_id

	merge 1:1 ind_id using `NSF', nogen
	
	merge 1:1 ind_id using "$directory\demographics", nogen
	
	merge 1:1 ind_id using `Income', nogen
	
	merge 1:1 ind_id using `Liquidity', nogen

	/*************************************************************************
	* 								TABLE 2									 *
	*************************************************************************/
	
	foreach var in wages income ca_bal sa_bal ccard_bal {
		count if `var' < .
		bysort everpayday: summ `var', detail
	}		
	
	/*************************************************************************
	* 					MERGING SURVEY DATA 								 *
	*************************************************************************/

	cap drop educ
	
	clonevar MENIGA_ID = ind_id
	tostring MENIGA_ID, force replace	
	
	sort MENIGA_ID

	merge 1:1 MENIGA_ID using "$directory/survey_data.dta", keepusing(MENIGA_ID DMA IES impatience presentbias educ)
	
	tab IES
	

	drop if _merge == 1
	drop _merge
	
	keep if DMA < .
		
	
	tempfile Analysis
	
	sort MENIGA_ID
	save `Analysis'

	/*************************************************************************
	* 								TABLE 3									 *
	*************************************************************************/
	
	use "$directory\payday_loans_merged.dta" if payday_loan > 0 & payday_loan < . & edate >= td(02sep2014), clear

	collapse (sum) payday_loan, by(ind_id edate) 	
	drop payday_loan
		
	sort ind_id edate
	merge 1:1 ind_id edate using `timeseries', keep(match) nogen

	gen temp = 1
	
	merge m:1 ind_id using `mean_exp', nogen keep(match)
	

	foreach var in ca sa_bal ccard ca_sa liq {
		replace `var' = `var'/mean_exp
		count if `var' < .
		summ `var', detail
	}
	
	egen ID = group(ind_id)
	summ ID
	
	/*************************************************************************
	* 								TABLE 5									 *
	*************************************************************************/
	
	use `Analysis', clear
	
	preserve
	
		summ loanamnt
		global totalamnt = r(sum)

		sort DMA loanamnt
		gen n = _n/_N
		forvalues i = 1(1)9 {
			clonevar temp = loanamnt
			replace temp = .	if n > `i'/10
			egen decile`i' = total(temp)
				replace decile`i' = decile`i'/$totalamnt
			drop temp
		}		
		
		summ decile*
	
	restore
	
	/*****************************************************************************
	* 			PROGRAM to GENERATE FIGURES with TERCILE BAR GRAPHS 			 *
	******************************************************************************/
	
	cap program drop bargraph
	program define bargraph
	
		* 1: bars on the left
		* 2: bars on the right
		* 3: terciles
		* 4: title x-axis
		* 5: title left  y-axis
		* 6: title right y-axis
		* 7: file name
		* 8: range left  y-axis
		* 9: range right y-axis
		* 10: legend group 1
		* 11: legend group 2
		* 12: legend group 3
		
		preserve
	
			*TESTS
			gen D2 = (`3' == 2)
			gen D3 = (`3' == 3)
			
			reg `1' D2	if `3' == 1 | `3' == 2, robust
			reg `1' D3	if `3' == 2 | `3' == 3, robust
			reg `1' D2 D3, robust
			test (D2) (D3)
	
			reg `2' D2	if `3' == 1 | `3' == 2, robust
			reg `2' D3	if `3' == 2 | `3' == 3, robust
			reg `2' D2 D3, robust
			test (D2) (D3)

			
			*** FIGURE
			gen X = _n
			gen Y = .
		
			summ `1'								if `3' 	== 1
			replace	Y = r(mean) 					if X 	== 1
			
			summ `1'								if `3' 	== 2
			replace	Y = r(mean) 					if X 	== 3
			
			summ `1'								if `3' 	== 3
			replace	Y = r(mean) 					if X	== 5
			
			summ `2'								if `3' 	== 1
			replace	Y = r(mean) 					if X 	== 9

			summ `2'								if `3' 	== 2
			replace	Y = r(mean) 					if X 	== 11
			
			summ `2'								if `3'	== 3
			replace	Y = r(mean) 					if X 	== 13
			
			twoway 	(bar Y X if X == 1,  fcolor(ltblue) 	lcolor(ltblue) 	yaxis(1))  		///
					(bar Y X if X == 3,  fcolor(midblue) 	lcolor(midblue) yaxis(1)) 		///
					(bar Y X if X == 5,  fcolor(navy) 		lcolor(navy) 	yaxis(1)) 		///
					(bar Y X if X == 9,  fcolor(ltblue) 	lcolor(ltblue) 	yaxis(2))  		///
					(bar Y X if X == 11, fcolor(midblue) 	lcolor(midblue) yaxis(2))  		///
					(bar Y X if X == 13, fcolor(navy) 		lcolor(navy) 	yaxis(2))		///
					, legend(order(1  "`10'" 2 "`11'" 3 "`12'") rows(1)) 					///
					xtitle("`4'") 															///
					legend(region(lwidth(none))) 											///
					yscale(titlegap(2))														///
					title("", size(medium)) ylabel(, nogrid) 								///
					xlabel(,labsize(small) labcolor(white) noticks) 						///
					ytitle("`5'", axis(1)) 													///
					ytitle("`6'", axis(2)) 													///
					ylabel(`8', axis(1))													///
					ylabel(`9', axis(2))													///
					scheme(s2mono) graphregion(fcolor(white))  
		
		restore	
		
	end
	
	/*************************************************************************
	* 							TERCILES								  	*
	*************************************************************************/

	xtile DMApctile   = DMA, nquantiles(99)
	xtile DMAtercile  = DMA, nquantiles(3)
	
	gen risktercile = .
		replace risktercile = 1	if IES >  .01333  & IES < .
		replace risktercile = 2	if IES >= .000295 & IES < .01333
		replace risktercile = 3	if IES <  .000295	
	
	gen timetercile = .
		replace timetercile = 1   if impatience == 0
		replace timetercile = 2   if impatience >  0  & impatience < 1/3
		replace timetercile = 3   if impatience > 1/3 & impatience < .
	
	gen PBtercile = .
		replace PBtercile = 1   if presentbias < 0
		replace PBtercile = 2   if presentbias == 0
		replace PBtercile = 3   if presentbias > 0 & presentbias < .
		
	xtile liqtercile = liquidity, nquantiles(3)
		
	/*************************************************************************
	* 							FIGURE 2									 *
	*************************************************************************/
	
	bargraph 	numloans loanamnt DMAtercile								 	///
				"Terciles of Distribution of Decision-making Ability" 			///
				"Average Number of Payday Loans" 								///
				"Average Total Amount Payday Loans (in 100s kr.)" 				///
				"Figure 3" 														///
				".4(.4)1.6" "100(100)400" 										///
				"Bottom" "Middle" "Top"
	
	/*************************************************************************
	* 							FIGURE 3									 *
	*************************************************************************/
	
	bargraph 	numloans DMApctile timetercile 									///
				"Fraction of Endowment Allocated to Sooner Date (1 Year Away)" 	///
				"Average Number of Payday Loans" 								///
				"Percentile Rank in Decision-making Ability Distribution" 		///
				"Figure 4A" 													///
				".6(.2)1.6"	"30(10)60" 											///
				"0%" "> 0% and < 33%" "> 33%"
				
	bargraph 	numloans DMApctile PBtercile 									///
				"" 																///
				"Average Number of Payday Loans" 								///
				"Percentile Rank in Decision-making Ability Distribution" 		///
				"Figure 4B" 													///
				".7(.175)1.4"	"40(5)60" 										///
				"Future Biased" "Time Consistent" "Present Biased"
				
	bargraph 	numloans DMApctile risktercile 									///
				"Terciles of Distribution of Risk Aversion" 					///
				"Average Number of Payday Loans" 								///
				"Percentile Rank in Decision-making Ability Distribution" 		///
				"Figure 4C" 													///
				".3(.3)1.2"	"40(5)60" 											///
				"Bottom" "Middle" "Top"
				
	bargraph 	numloans DMApctile liqtercile 									///
				"Terciles of Distribution of Liquidity" 						///
				"Average Number of Payday Loans" 								///
				"Percentile Rank in Decision-making Ability Distribution" 		///
				"Figure 4D" 													/// 
				"0(.5)2.5"	"46(2)54"											///
				"Bottom" "Middle" "Top"
				

	drop DMAtercile DMApctile risktercile timetercile PBtercile liqtercile
	
	/*************************************************************************
	* 						SAMPLE RESTRICTION								 *
	*************************************************************************/

	foreach var in everpayday DMA IES female age educ income impatience presentbias liquidity { 
		drop if `var' >= .
	}	
	
	/*************************************************************************
	* 							Age Squared									 *
	*************************************************************************/
	
	summ age
	replace age = age - r(mean)
	gen age2 = age ^ 2
	
	/*************************************************************************
	* 				      	PERCENTILE RANKS								 *
	*************************************************************************/
				
	gen riskaversion = - IES
				
	foreach var in DMA impatience presentbias liquidity riskaversion {
	
		xtile temp = `var', nquantiles(99)
		drop `var'
		ren temp `var'
		replace `var' = `var'/10
	
	}
	
	drop IES
	
	/*************************************************************************
	* 							LOG INCOME				     				 *
	*************************************************************************/
	
	replace income = ln(income)
	
	tempfile Regressions
	
	
	sort MENIGA_ID
	save `Regressions'
	
	/*************************************************************************
	* 							TABLE 6										 *
	*************************************************************************/
	
	global controls "income educ female age age2"
	global timepref "impatience presentbias"
	global riskpref "riskaversion"	
	
	mean numloans
						
	regress	numloans 	DMA	 										$controls, robust
		
	regress	numloans 			liquidity	 						$controls, robust
		
	regress	numloans 	DMA 	liquidity 							$controls, robust
		
	regress	numloans 	DMA 	liquidity	$timepref 				$controls, robust
		
	regress	numloans 	DMA 	liquidity	$timepref	$riskpref	$controls, robust		
	
	/*************************************************************************
	* 							FIGURE 4									 *
	*************************************************************************/
		
	preserve
	
		use `Analysis', clear
	
		xtile temp1 = liquidity, nquantiles(2)
		xtile temp2 = DMA, nquantiles(2)
		
		gen highliq = (temp1 == 2)
		gen highDMA = (temp2 == 2)
		
		gen Lliq_LDMA = (highliq == 0 & highDMA == 0)
		gen Lliq_HDMA = (highliq == 0 & highDMA == 1) 
		gen Hliq_LDMA = (highliq == 1 & highDMA == 0)
		gen Hliq_HDMA = (highliq == 1 & highDMA == 1)
				
		* TESTS		
		reg numloans Lliq_HDMA	if Lliq_LDMA == 1 | Lliq_HDMA == 1, robust 
		reg numloans Hliq_LDMA	if Lliq_HDMA == 1 | Hliq_LDMA == 1, robust 		
		reg numloans Hliq_HDMA	if Hliq_LDMA == 1 | Hliq_HDMA == 1, robust 
				
		reg numloans Lliq_HDMA Hliq_LDMA Hliq_HDMA, robust
		test (Lliq_HDMA) (Hliq_LDMA) (Hliq_HDMA)
		
		* FIGURE
		gen X = _n
		gen Y = .
						
		reg numloans								if highliq == 0 & highDMA == 0 
		replace	Y = _b[_cons] 						if X == 1
			
		reg numloans								if highliq == 0 & highDMA == 1
		replace	Y = _b[_cons] 						if X == 3
			
		reg numloans								if highliq == 1 & highDMA == 0
		replace	Y = _b[_cons] 						if X == 5

		reg numloans								if highliq == 1 & highDMA == 1
		replace	Y = _b[_cons] 						if X == 7
		
		twoway 	(bar Y X if X == 1,  fcolor(gs12) 	lcolor(gs12)) 		/// 
				(bar Y X if X == 3,  fcolor(gs8) 	lcolor(gs8)) 		/// 
				(bar Y X if X == 5,  fcolor(gs4) 	lcolor(gs4)) 		/// 
				(bar Y X if X == 7,  fcolor(gs0) 	lcolor(gs0)) 		/// 
				, legend(order(1 "Illiquid, Low DMA" 2 "Illiquid, High DMA" 3 "Liquid, Low DMA" 4 "Liquid, High DMA") rows(2)) 	///
				 title("", size(medium)) ylabel(, nogrid) xtitle("") 					/// 				  					
				 xlabel(,labsize(small) labcolor(white) noticks) 						///
				 ytitle("Average Number of Payday Loans") 		///
				 scheme(s2mono) graphregion(fcolor(white))  

	restore		
		
	/*************************************************************************
	* 							TABLE 7										 *
	*************************************************************************/
	
	summ DMA
	replace DMA = DMA - r(mean)
	
	summ liquidity
	replace liquidity = liquidity - r(mean)
	
	gen interaction = liquidity * DMA
	
	
	mean numloans
						
	regress	numloans 				DMA 	liquidity 							$controls, robust
		
	regress	numloans 	interaction	DMA 	liquidity 							$controls, robust
		
	regress	numloans 	interaction	DMA 	liquidity	$timepref 				$controls, robust
		
	regress	numloans 	interaction	DMA 	liquidity	$timepref	$riskpref	$controls, robust
		
	/*************************************************************************
	* 							TABLE 9										 *
	*************************************************************************/
	
	mean numNSF
						
	regress	numNSF 					DMA	 										$controls, robust
		
	regress	numNSF 							liquidity	 						$controls, robust
		
	regress	numNSF 					DMA 	liquidity 							$controls, robust
		
	regress	numNSF 					DMA 	liquidity	$timepref	$riskpref	$controls, robust
		
	regress	numNSF 		interaction	DMA 	liquidity 							$controls, robust
		
	regress	numNSF		interaction	DMA 	liquidity	$timepref	$riskpref	$controls, robust

	/*************************************************************************
	* 					SUMMARY STATISTICS of NSF FEES   					 *
	*************************************************************************/

	preserve
	
		keep if e(sample) == 1
	
	
		keep MENIGA_ID
		
		
		tempfile NSFsample
		
		
		sort MENIGA_ID
		save `NSFsample'
	
	
		use "$directory\penalty_payments_ready.dta", clear

		
		clonevar MENIGA_ID = ind_id
		tostring MENIGA_ID, force replace
		
		replace fit = -fit/100
	
		merge m:1 MENIGA_ID using `NSFsample', keep(match) nogen

		********************************************************	
		*** 		AT THE LEVEL of THE MONTH 				***	
		********************************************************	

		gen fit_percount = fit/fit_count
			replace fit_percount = 0	if fit_count == 0
		
		count if fit < .
		count if fit < . & fit > 0
		
		count if fit_count < .
		count if fit_count < . & fit > 0
		
		summ fit, detail
		summ fit 			if fit > 0, detail
		summ fit_count, detail
		summ fit_count 		if fit_count > 0, detail
		summ fit_percount, detail
		summ fit_percount	if fit_percount > 0, detail
		
		********************************************************	
	
		collapse (sum) fit_count (sum) fit (mean) fit_percount, by(MENIGA_ID)
		
		********************************************************	
		***  			AT INDIVIDUAL-LEVEL					***	
		********************************************************	

		count if fit < .
		count if fit < . & fit > 0
		
		count if fit_count < .
		count if fit_count < . & fit > 0

		summ fit, detail
		summ fit 			if fit > 0, detail
		summ fit_count, detail
		summ fit_count 		if fit_count > 0, detail
		summ fit_percount, detail
		summ fit_percount	if fit_percount > 0, detail
		
		********************************************************	
	
	
	restore
				
	/*************************************************************************
	* 							TABLE 10									 *
	*************************************************************************/
	
	replace everpayday = everpayday * 100
	
	keep everpayday DMA	riskaversion income educ female age age2
	
						
	tempfile Meniga
	save `Meniga'
		
	global controls1 	"female age age2"
	global controls2 	"income educ" 	
	global riskpref 	"riskaversion"
	
	use `Meniga', clear				
	mean everpayday
	regress	everpayday	DMA	 								  , robust
		
	use "$directory/UAS_PaydayLoans", clear
	mean everpayday
	regress	everpayday	DMA	 								  , cluster(uasid)
		
	use `Meniga', clear				
	regress	everpayday 	DMA	 						$controls1, robust
		
	use "$directory/UAS_PaydayLoans", clear
	regress	everpayday	DMA	 						$controls1 Mdemographics, cluster(uasid)

	use `Meniga', clear				
	regress	everpayday 	DMA				$controls2	$controls1, robust
		
	use "$directory/UAS_PaydayLoans", clear
	regress	everpayday 	DMA				$controls2	$controls1 Mdemographics Meducation Mincome, cluster(uasid)
		
	use `Meniga', clear				
	regress	everpayday 	DMA	$riskpref	$controls2	$controls1, robust
	
	use "$directory/UAS_PaydayLoans", clear
	regress	everpayday	DMA	$riskpref	$controls2	$controls1 Mdemographics Meducation Mincome, cluster(uasid)
	
	/*************************************************************************
	* 							TABLE 8									 *
	*************************************************************************/
	
	/*************************************************************************
	* 					ANALYSIS at DAILY LEVEL 							 *
	*************************************************************************/
	
	/*************************************************************************
	* 						DAILY PAYDAY LOANS								 *
	*************************************************************************/
	
	use "$directory\payday_loans_merged.dta" if edate >= td(02sep2014), clear 

	gen loan = (payday_loan > 0) if payday_loan < .
		
	clonevar MENIGA_ID = ind_id
	tostring MENIGA_ID, force replace

	collapse (sum) loan, by(MENIGA_ID edate) 	
	tab loan, mi
	
	replace loan = 1	if loan > 1 & loan < .

	tempfile DailyPayday
	
	sort MENIGA_ID edate
	save `DailyPayday'
	
	
	preserve
	
		collapse (max) loan, by(MENIGA_ID)
		mean loan
	
	restore
		
	/*************************************************************************
	* 						DAILY LIQUIDITY									 *
	*************************************************************************/
		
	use "$directory\accounts_2014_2017.dta", clear

	clonevar MENIGA_ID = ind_id
	tostring MENIGA_ID, force replace

		/*********************************************************************
		* Adjusting for when overdraft or credit card exceeded limits		 *
		*********************************************************************/

		replace sa_bal = 0	if sa_bal < 0
		replace ca_lim = -ca_bal		if ca_bal < 0 		& abs(ca_bal) > ca_lim
		replace ccard_lim = -ccard_bal	if ccard_bal < 0 	& abs(ccard_bal) > ccard_lim

	
	gen liq  = ca_lim + ca_bal + ccard_lim + ccard_bal + sa_bal
	replace liq = liq/100
	
	summ liq
	
	keep MENIGA_ID edate liq
		
	replace edate = edate + 1	
		
	egen id = group(MENIGA_ID)
	qui summ id
	global rmax = r(max)
	

	compress
	

	tempfile DailyLiq
	
	sort MENIGA_ID edate
	save `DailyLiq'
		
	/*************************************************************************
	* 			WITHIN-PARTICIPANT PERCENTILE RANK 							 *
	*************************************************************************/

	qui {
	
		forvalues i = 1/$rmax {
		
			use `DailyLiq'	if id == `i', clear
			
			foreach var in liq { 
				xtile PR`var' = `var', nquantiles(99)
			}
			
			keep MENIGA_ID edate PRliq 
			
			tempfile PR`i'
			
			sort MENIGA_ID edate
			save `PR`i''
			
		}
		
		use `PR1', clear
		
		forvalues i = 2/$rmax {	
			append using `PR`i''
		}
		
		foreach var in liq { 
			replace PR`var' = PR`var'/10
		}

		compress
		
		tempfile PRLiq
		
		sort MENIGA_ID edate
		save `PRLiq'
		
	}
	
	/*************************************************************************
	* 					MERGING DATA at DAILY LEVEL		 					 *
	*************************************************************************/
	
	use `DailyPayday', clear
	
	sort MENIGA_ID edate
	merge 1:1 MENIGA_ID edate using `DailyLiq'
	keep if _merge == 3
	drop _merge

	sort MENIGA_ID edate
	merge 1:1 MENIGA_ID edate using `PRLiq'
	keep if _merge == 3
	drop _merge

	/*************************************************************************
	* 				MERGING with TIME-INVARIANT DATA	 					 *
	*************************************************************************/
	
	sort MENIGA_ID
	merge m:1 MENIGA_ID using `Regressions', keepusing(MENIGA_ID DMA impatience presentbias riskaversion income educ female age age2)
	keep if _merge == 3
	drop _merge
	
	/*************************************************************************
	* 						SAMPLE RESTRICTION								 *
	*************************************************************************/

	foreach var in loan DMA liq impatience presentbias riskaversion income educ female age  {
		drop if `var' >= .
	}	
	
	/*************************************************************************
	* 			INVERSE HYPERBOLIC SINE of BALANCES						     *
	*************************************************************************/

	foreach var in liq { 
		gen IHS`var' = ln(`var' + (`var'^2 + 1)^.5)
	}		
		
	/*************************************************************************
	* CALENDAR DAY of the MONTH and DAY-of-THE-WEEK FIXED EFFECTS		     *
	*************************************************************************/

	gen day = day(edate)
		replace day = 30	if day == 31
	tab day, gen(DAYS)
	drop DAYS1 day
		
	gen week = dow(edate)
	tab week, gen(WEEK)
	drop WEEK2 week
	
	/*************************************************************************
	* 		RESULTS IN TERMS of a HUNDREDTH of a PERCENTAGE POINT 			 *
	*************************************************************************/

	replace loan = loan * 10000
	
	/*************************************************************************
	* 							TABLE 8									 *
	*************************************************************************/
	
	global controls 	"income educ female age age2 DAYS* WEEK*"
	global timepref 	"impatience presentbias"
	global riskpref 	"riskaversion"
	
	local liquidity1	"liq"
	local liquidity2	"IHSliq"
	local liquidity3	"PRliq"
	
	replace liq = liq/10000
	
	mean loan
						
		regress	loan 	DMA	 											$controls, cluster(MENIGA_ID)
	
		regress	loan 	DMA 	`liquidity1' 							$controls, cluster(MENIGA_ID)
	
		regress	loan 	DMA 	`liquidity1'	$timepref				$controls, cluster(MENIGA_ID)
	
	forvalues i = 1/3 {
		
		regress	loan 	DMA 	`liquidity`i''	$timepref	$riskpref	$controls, cluster(MENIGA_ID)
	
	}

	/*************************************************************************
	* 							FIGURE 1									 *
	*************************************************************************/
	
	/*************************************************************************
	* 						-30/+30 days around loans						 *
	*************************************************************************/
	
	use "$directory\payday_loans_merged.dta" if payday_loan > 0 & payday_loan < ., clear

	keep if edate >= td(01oct2014) & edate <= td(14jan2017)
	keep ind_id edate
	
	forvalues i = 1/61 {
		clonevar date`i' = edate
		replace date`i' = date`i' + `i' - 31  
	}		
		
	sort ind_id edate
	by ind_id: gen loan_number = _n
	
	drop edate
	reshape long date, i(ind_id loan_number) j(k)
	ren date edate
	
	replace k = k - 31

	
	tempfile loans
	
	sort ind_id edate
	save `loans'
	
	/*************************************************************************
	* 						Identifying borrowers							 *
	*************************************************************************/
	
	collapse (mean) edate, by(ind_id)
	drop edate
			
	tempfile borrowers
	
	sort ind_id
	save `borrowers'
		
	/*************************************************************************
	* 						Balance Data					   				 *
	*************************************************************************/
	
	use "$directory\accounts_2014_2017.dta", clear
	

	merge m:1 ind_id using `borrowers'
	tab _merge
	keep if _merge == 3
	drop _merge

		/*********************************************************************
		* Adjusting for when overdraft or credit card exceeded limits		 *
		*********************************************************************/

		replace sa_bal = 0	if sa_bal < 0
		replace ca_lim = -ca_bal		if ca_bal < 0 		& abs(ca_bal) > ca_lim
		replace ccard_lim = -ccard_bal	if ccard_bal < 0 	& abs(ccard_bal) > ccard_lim

	
	gen liquidity  = (ca_bal + ccard_bal + sa_bal + ccard_lim + ca_lim)/100

	keep ind_id edate liquidity
	
	/*************************************************************************
	* 			Merging average daily expenditure 							 *
	*************************************************************************/
	
	merge m:1 ind_id using `mean_exp', keep(match) nogen			

	
	replace liquidity = liquidity/mean_exp
			
			
		
	keep ind_id edate liquidity
	
	
	tempfile balance
	
	sort ind_id edate
	save `balance'
	
	
	
	use `loans', clear
	
	merge m:1 ind_id edate using `balance', keep(match) nogen

	/*************************************************************************
	* 					Counting Number of Observations	 					 *
	*************************************************************************/
	
	* total number of individual x days
	count if k == 0
	
	* number of individuals
	egen nobs = group(ind_id)
	summ nobs
	drop nobs
	
	/*************************************************************************
	* 							Time Event Graph			 				 *
	*************************************************************************/
	
	cap program drop fig1
	program define fig1, rclass
	
		forvalues i = 1/61 {
			
			local k = `i' - 31
			summ liquidity if k == `k', detail
			return scalar r`i' = r(p50)
		
		}
		
	end	
	
	bootstrap 	r1=r(r1) ///
				r2=r(r2) ///
				r3=r(r3) ///
				r4=r(r4) ///
				r5=r(r5) ///
				r6=r(r6) ///
				r7=r(r7) ///
				r8=r(r8) ///
				r9=r(r9) ///
				r10=r(r10) ///
				r11=r(r11) ///
				r12=r(r12) ///
				r13=r(r13) ///
				r14=r(r14) ///
				r15=r(r15) ///
				r16=r(r16) ///
				r17=r(r17) ///
				r18=r(r18) ///
				r19=r(r19) ///
				r20=r(r20) ///
				r21=r(r21) ///
				r22=r(r22) ///
				r23=r(r23) ///
				r24=r(r24) ///
				r25=r(r25) ///
				r26=r(r26) ///
				r27=r(r27) ///
				r28=r(r28) ///
				r29=r(r29) ///
				r30=r(r30) ///
				r31=r(r31) ///
				r32=r(r32) ///
				r33=r(r33) ///
				r34=r(r34) ///
				r35=r(r35) ///
				r36=r(r36) ///
				r37=r(r37) ///
				r38=r(r38) ///
				r39=r(r39) ///
				r40=r(r40) ///
				r41=r(r41) ///
				r42=r(r42) ///
				r43=r(r43) ///
				r44=r(r44) ///
				r45=r(r45) ///
				r46=r(r46) ///
				r47=r(r47) ///
				r48=r(r48) ///
				r49=r(r49) ///
				r50=r(r50) ///
				r51=r(r51) ///
				r52=r(r52) ///
				r53=r(r53) ///
				r54=r(r54) ///
				r55=r(r55) ///
				r56=r(r56) ///
				r57=r(r57) ///
				r58=r(r58) ///
				r59=r(r59) ///
				r60=r(r60) ///
				r61=r(r61) ///
				, reps(500) strata(ind_id) nodrop seed(78269259): fig1		
		
		
			gen b = .
			gen lb = .
			gen ub = .
			
		
			forvalues k = -30/30 {
				
				local i = `k' + 31
				replace b = _b[r`i'] 						if k == `k'
				replace lb = _b[r`i'] - 1.96 * _se[r`i'] 	if k == `k'
				replace ub = _b[r`i'] + 1.96 * _se[r`i'] 	if k == `k'
	
			}
	
		twoway 	(rarea ub lb k, sort color(gs4%30))  	///
				(scatter b k, mcolor(black) msymbol(O)) 		/// 
				, ylabel(, nogrid) graphregion(fcolor(white)) 	///
				xline(0,  lpattern(solid) lcolor(black) lwidth(vthin)) 			///
				xtitle("Number of Days Before and After Payday Loan") ///
				ytitle("Liquidity in Days of Average Spending", size(medsmall))  /// 
				title("") legend(off) xlabel(-30 "-30" -20 "-20" -10 "-10" 0 "0" 10 "10" 20 "20" 30 "30")
				
	restore

	/*************************************************************************
	* To Calculate Total Number of Loans	 				 				 *
	*************************************************************************/
	
	tempfile finalsample
	
	keep if MDUMMIES31 == 1
	
	sort ind_id edate
	save `finalsample'
	
	preserve
	
		use "$directory\payday_loans_merged.dta" if payday_loan > 0 & payday_loan < ., clear

		keep if edate >= td(01oct2014) & edate <= td(14jan2017)
		keep ind_id edate
		
		merge m:1 ind_id edate using `finalsample'
		tab _merge
		keep if _merge == 3
		
		* total number of loans
		count
		
		gen numloans = 1
		
		collapse (sum) numloans, by(ind_id)
		
		* distribution of number of loans across individuals
		summ numloans, detail
		
	restore
	
	/*************************************************************************
	* 						FIGURE 5 & FIGURE 6					 			 *
	*************************************************************************/
	
	/*************************************************************************
	* 					FINANCIAL AGGREGATION DATA 							 *
	*************************************************************************/
	/*************************************************************************
	* 							PAYDAY LOANS								 *
	*************************************************************************/

	use "$directory\payday_loans_merged.dta", clear

	
	gen loan = (payday_loan > 0) if payday_loan < .
	
	collapse (sum) loan, by(ind_id edate)
	
	
	tempfile Payday_Loans
	
	sort ind_id edate
	save `Payday_Loans'	
	
	/*************************************************************************
	* 							LIQUIDITY									 *
	*************************************************************************/
		
	use "$directory\accounts_2014_2017.dta", clear

	merge m:1 ind_id using `mean_exp', nogen keep(match)
	
	
		/*********************************************************************
		* Adjusting for when overdraft or credit card exceeded limits		 *
		*********************************************************************/

		replace sa_bal = 0	if sa_bal < 0
		replace ca_lim = -ca_bal		if ca_bal < 0 		& abs(ca_bal) > ca_lim
		replace ccard_lim = -ccard_bal	if ccard_bal < 0 	& abs(ccard_bal) > ccard_lim

	
		gen liq  = (ca_lim + ca_bal + ccard_lim + ccard_bal + sa_bal)/mean_exp
		replace liq = liq/100
		
		keep ind_id edate liq
	
	sort ind_id edate
	merge 1:1 ind_id edate using `Payday_Loans', nogen


	compress

	tempfile Liquidity_and_Loans
	
	
	sort ind_id edate
	save `Liquidity_and_Loans'
	*/
	/*************************************************************************
	* 	IDENTIFYING CALENDAR DAY OF THE MONTH in WHICH SURVEY was TAKEN 	 *
	*************************************************************************/

	use MENIGA_ID begintime using "$directory/survey_data.dta", clear
		
	gen double temp1 = clock(begintime, "YMDhms")
	gen temp2 = dofc(temp1)
	gen day = day(temp2)
	replace day = 30	if day == 31
			
	keep MENIGA_ID day 
				
	/*********************************************************************************
	* CALCULATING AVERAGE DMA BY CALENDAR DAY OF THE MONTH in WHICH SURVEY was TAKEN *
	**********************************************************************************/

	sort MENIGA_ID
	merge 1:1 MENIGA_ID using "$directory/survey_data.dta", keepusing(MENIGA_ID DMA)
	keep if _merge == 3
	drop _merge
		
	keep if DMA < .
		

	xtile temp = DMA, nquantiles(99)
	drop DMA
	ren temp DMA
	
	keep if day < .
	
	count
	
	reg DMA day, r
	
	global a = _b[_cons]
	global b = _b[day]
	
	gen pop = 1

	collapse (mean) DMA (sum) pop, by(day)
		
		
	tempfile DMA
		
	sort day
	save `DMA'
	
	/*********************************************************************************
	* CALCULATING AVERAGE DMA BY CALENDAR DAY OF THE MONTH in WHICH SURVEY was TAKEN *
	**********************************************************************************/

	use `Liquidity_and_Loans', clear

	gen day = day(edate)
	replace day = 30 if day == 31

	
	count if liq < .  & day < .
	count if loan < . & day < .
	
	collapse (mean) liq (mean) loan, by(day)

	summ liq, detail
	
	merge 1:1 day using `DMA', nogen
	
	gen xb = $a + ($b * day)
	
	replace loan = loan*(100)
	
	/*************************************************************************
	* 								FIGURE 5					 			 *
	*************************************************************************/
	
	twoway (scatter liq day, yaxis(1) msymbol(X) mcolor(black) msize(vlarge)) ///
		   (scatter loan day, yaxis(2) msymbol(Oh) mcolor(red) msize(medlarge)) ///
		   , ylabel(, nogrid) graphregion(fcolor(white)) 	///
		   xtitle("Calendar Day of the Month") ///
		   ytitle("Liquidity in Days of Average Spending", axis(1))  /// 
		   ytitle("Fraction who Took a Loan (in PPs)", axis(2))  /// 
		   title("") legend(order(1 "Liquidity" 2 "Payday Loans") ring(0) position(6))
		   
	/*************************************************************************
	* 								FIGURE 6					 			 *
	*************************************************************************/
		
	twoway (scatter liq day, yaxis(1) msymbol(X) mcolor(black) msize(vlarge)) ///
		   (scatter DMA day [fw = pop], yaxis(2) msymbol(Oh) mcolor(red) msize(medlarge)) ///
		   (line xb day, yaxis(2) lcolor(red)) ///
		   , ylabel(, nogrid) graphregion(fcolor(white)) 	///
		   xtitle("Calendar Day of the Month") ///
		   ytitle("Liquidity in Days of Average Spending", axis(1))  /// 
		   ytitle("Average Percentile Rank of Decision-Making Ability", axis(2))  /// 
		   title("") legend(order(1 "Liquidity" 2 "DMA") ring(0) position(6))  	
